from datetime import timedelta

from odoo import models, fields, api
from odoo.exceptions import ValidationError


class HrAttendanceWizard(models.TransientModel):
    _name = 'hr.attendance.wizard'
    start_date=fields.Date(string=u'开始日期')
    end_date=fields.Date(string=u'结束日期',default=fields.date.today())
    department_id=fields.Many2one('hr.department')
    employee_id=fields.Many2one('hr.employee')
    employee_type = fields.Selection([
        ('1', '月薪'),
        ('2', '日薪'),
        ('3', '小时工')
    ], string=u'职工类型')
    attendance_type=fields.Selection([
        ('1','正常'),
        ('0', '异常'),
    ],string='状态')
    ab_type=fields.Selection([
        ('1','迟到'),
        ('2', '早退'),
        ('3','旷工')
    ],string=u'异常类型')



    def action_confirm(self):
        if not self.department_id:
            employee_ids=self.env['hr.employee'].search([])
        else:
            employee_ids = self.env['hr.employee'].search([('department_id','=',self.department_id.id)])
        if self.employee_id:
            employee_ids=[self.employee_id]
        date=self.start_date
        reports=self.env['hr.attendance.report']
        while  date<=self.end_date:
            for e in employee_ids:
                domain=[('employee_id','=',e.id),('date','=',date.strftime('%Y-%m-%d'))]
                attendance_id = self.env['hr.attendance'].search(domain)
                report_id=reports.search(domain)
                if not report_id:

                    report_id=reports.create({
                        'employee_id':e.id,
                        'attendance_id':attendance_id.id,
                        'date':date
                    })
                report_id.write({
                    'employee_id': e.id,
                    'attendance_id':attendance_id.id,
                    'date': date
                })
                report_id.compute_report_type()
                reports|=report_id
            date=date+timedelta(days=1)
        if self.attendance_type=='1':
            reports=reports.filtered(lambda x:x.attendance_type=='1')
        if self.attendance_type=='0' and not self.ab_type:
            reports=reports.filtered(lambda x:x.attendance_type=='0')
        elif self.attendance_type=='0' and self.ab_type=='1':
            reports=reports.filtered(lambda x:x.attendance_type=='0' and x.is_late==True)
        elif self.attendance_type=='0' and self.ab_type=='2':
            reports=reports.filtered(lambda x:x.attendance_type=='0' and  x.is_leave_early==True)
        elif self.attendance_type=='0' and self.ab_type=='3':
            reports=reports.filtered(lambda x:x.attendance_type=='0' and  x.is_absent==True)


        return {'type': 'ir.actions.act_window',
                'res_model': 'hr.attendance.report',
                'name': u'考勤日报表',
                'view_mode': 'tree',
                'domain': [('id', 'in', reports.ids)],
                'target': 'self',
                }

